package com.haofengsoft.platform.companent.imageview.webimageview;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by weiwei on 15/6/7.
 */
public class WebImageView extends ImageView {

    public WebImageView(Context context) {
        super(context);
    }

    public WebImageView(Context context, AttributeSet attSet) {
        super(context, attSet);
    }

    public static void setMemoryCachingEnabled(boolean enabled) {
        WebImageCache.setMemoryCachingEnabled(enabled);
    }

    public static void setDiskCachingEnabled(boolean enabled) {
        WebImageCache.setDiskCachingEnabled(enabled);
    }

    public static void setDiskCachingDefaultCacheTimeout(int seconds) {
        WebImageCache.setDiskCachingDefaultCacheTimeout(seconds);
    }

    @Override
    public void onDetachedFromWindow() {
        // cancel loading if view is removed
        cancelCurrentLoad();
    }

    public void setImageWithURL(Context context, String urlString, Drawable placeholderDrawable, int diskCacheTimeoutInSeconds) {
        final WebImageManager mgr = WebImageManager.getInstance();

        cancelCurrentLoad();
        setImageDrawable(placeholderDrawable);

        if (urlString != null) {
            mgr.downloadURL(context, urlString, WebImageView.this, diskCacheTimeoutInSeconds);
        }
    }

    public void setImageWithURL(Context context, String urlString, Drawable placeholderDrawable) {
        setImageWithURL(context, urlString, placeholderDrawable, -1);
    }

    public void setImageWithURL(final Context context, final String urlString, int diskCacheTimeoutInSeconds) {
        setImageWithURL(context, urlString, null, diskCacheTimeoutInSeconds);
    }

    public void setImageWithURL(final Context context, final String urlString) {
        setImageWithURL(context, urlString, null, -1);
    }

    public void cancelCurrentLoad() {
        WebImageManager mgr = WebImageManager.getInstance();
        // cancel any existing request
        mgr.cancelForWebImageView(this);
    }

}
